<?php
/**
 * 财务管理控制器
 * User: 吴
 * Date: 2019/3/19 0012
 * Time: 下午 15:20
 */

namespace app\admin\controller;

use think\Db;
use think\Request;
use cmf\controller\AdminBaseController;


class FinanceController extends AdminBaseController{


    /**
     * 财务列表
     */
    public function index(){
        $where = '';
        if($this->request->isPost()){
           if(!empty($_POST['scene'])){
              $where .= 'scene = '.$_POST['scene'];
           }
           if(!empty($_POST['user_name']) && !empty($where)){
              $user = Db::name('shop_user')->where('user_name',$_POST['user_name'])->find();
              if(!empty($user)){
                $where .= ' AND user_id = '.$user['user_id'];
              }
           }else if(!empty($_POST['user_name']) && empty($where)){
              $user = Db::name('shop_user')->where('user_name',$_POST['user_name'])->find();
              if(!empty($user)){
                $where .= 'user_id = '.$user['user_id'];
              }
           }
        }
        $export = '';
        if($this->request->isGet()){
          if(!empty($_GET['scene'])){
              $where .= 'scene = '.$_GET['scene'];
          }
          if(!empty($_GET['type'])){
              $export = $_GET['type'];
          }
        }
        if(empty($export)){
           $data = Db::name('balance_record')
                ->where($where)
                ->order('id desc')
                ->paginate(10) 
                ->toarray();
        }else{
           $data = Db::name('balance_record')
                ->where($where)
                ->order('id desc')
                ->paginate(1000000)
                ->toarray();
        }
        $data1 = Db::name('balance_record')
               ->where($where)
               ->order('id desc')
               ->paginate(10);
        $order = array();
        $recharge = array();
        $fetch = array();
        $user_ids = array();
        if(!empty($data)){
          foreach ($data['data'] as $k => $v) {
            if($v['scene'] == 3 || $v['scene'] == 4 || $v['scene'] == 5){
               $order[] = $v['data_id']; 
            }if($v['scene'] == 2){
               $recharge[] = $v['data_id'];
            }else{
               $fetch[] = $v['data_id'];
            }
            $user_ids[] = $v['user_id'];
          }
          if(count($user_ids) > 1){
             $user_ids = implode(',',array_unique($user_ids));
          }
          $user_info = Db::name('shop_user')->where('user_id','in',$user_ids)->field('mobile,user_id')->select()->toarray();
          foreach ($data['data'] as $k => $v) {
            $data['data'][$k]['mobile'] = '';
            foreach ($user_info as $i => $j) {
               if($v['user_id'] == $j['user_id']){
                  $data['data'][$k]['mobile'] = $j['mobile'];
               }
            }
          }
          if(!empty($order)){
            if(count($order) > 1){
               $ids = implode(',',array_unique($order));
            }else{
               $ids = $order;
            }
            $order_info = Db::name('order')
                      ->field('order_no,payment_type,order_id')
                      ->where('order_id','in',$ids)
                      ->select()
                      ->toarray();
            $payment_type = [
               '1'        => '余额支付',
               '2'        => '微信支付',
               '3'        => '支付宝支付',
            ];
            foreach ($data['data'] as $k => $v) {
              foreach ($order_info as $key => $value) {
                if($v['data_id'] == $value['order_id']){
                  $data['data'][$k]['order_no']     = $value['order_no'];
                  $data['data'][$k]['payment_type'] = $payment_type[$value['payment_type']];
                  $data['data'][$k]['status']       = -1;
                  $data['data'][$k]['type']         = '已完成';
                }
              }
            }
          } 
          //充值
          if(!empty($recharge)){
            if(count($recharge) > 1){
               $recharge_ids = implode(',',array_unique($recharge));
            }else{
               $recharge_ids = $recharge;
            }
            $info = Db::name('recharge')
                  ->field('order_sn,type,id,status')
                  ->where('id','in',$recharge_ids)
                  ->select()
                  ->toarray();
            $type = array('后台充值','微信支付','支付宝支付');
            foreach ($data['data'] as $k => $v) {
              foreach ($info as $i => $j) {
                if($v['data_id'] == $j['id']){
                  if($j['status'] == 1){
                    $status = '待支付';
                  }else{
                    $status = '已支付';
                  }
                    $data['data'][$k]['order_no']     = $j['order_sn'];
                    $data['data'][$k]['payment_type'] = $type[$j['type']];
                    $data['data'][$k]['status']       = -1;
                    $data['data'][$k]['type']         = $status;
                }
              }
            }
          }
          //提现
          if(!empty($fetch)){
            if(count($fetch) > 1){
               $fetch_ids = implode(',',array_unique($fetch));
            }else{
               $fetch_ids = $fetch;
            }
            $fetch_info = Db::name('cash_record')
                        ->field('order_sn,status,id,status')
                        ->where('id','in',$fetch_ids)
                        ->select()
                        ->toarray();
            $fetch_status = [
                '1'       => '待处理',
                '2'       => '已完成',
                '3'       => '已拒绝',
                '4'       => '订单异常'
            ];
            foreach ($data['data'] as $k => $v) {
              foreach ($fetch_info as $i => $j) {
                if($v['data_id'] == $j['id']){
                    $data['data'][$k]['order_no']     = $j['order_sn'];
                    $data['data'][$k]['payment_type'] = '提现到银行卡';
                    $data['data'][$k]['status']       = $j['status'];
                    $data['data'][$k]['type']         = $fetch_status[$j['status']];
                }
              }
            }

          }
          $scene = [
            '1'  => '提现',
            '2'  => '充值',
            '3'  => '退款',
            '4'  => '消费',
            '5'  => '奖励',
          ]; 
          foreach ($data['data'] as $k => $v) {
            $data['data'][$k]['group'] = $scene[$v['scene']];
          }
        }
        if($export == 1){
          $this->export($data['data']);
        }else{
          $page = $data1->render();
          $total = $data1->total();
          $this->assign('page',$page);
          $this->assign('data',$data);
          $this->assign('total',$total);
          return $this->fetch();
        }  
    }


    /**
     * 详情
     */
    public function details(){
        $id = $this->request->get('id');
        $status = $this->request->get('status');
        $data = array();
        $level = ['普通会员','黄金会员','铂金会员','区代理','市代理','省代理'];
        if($status == 3 || $status == 4 || $status == 5){
            $data = Db::name('balance_record')
                  ->alias('a')
                  ->field('a.*,b.order_no,b.goods_name,b.goods_price,b.number,b.payment_type,b.order_money,b.user_name,c.level,c.mobile,c.oneself_volume,c.first_volume,c.second_volume')
                  ->join('order b','a.data_id = b.order_id','left')
                  ->join('shop_user c','a.user_id = c.user_id','left')
                  ->where('a.id = '.$id)
                  ->find();
           
        }else if($status == 2){
            $data = Db::name('balance_record')
                  ->alias('a')
                  ->field('a.*,b.order_sn,b.status,b.type,c.level,c.mobile,c.oneself_volume,c.first_volume,c.second_volume')
                  ->join('recharge b','a.data_id = b.id','left')
                  ->join('shop_user c','a.user_id = c.user_id','left')
                  ->where('a.id = '.$id)
                  ->find();
            $type = array('后台充值','微信支付','支付宝支付');
            $data['type'] = $type[$data['type']];
        }else{
            $data = Db::name('balance_record')
                  ->alias('a')
                  ->field('a.*,b.order_sn,b.status,b.money,b.fee_money,c.level,c.mobile,c.oneself_volume,c.first_volume,c.second_volume,d.credit_num,d.credit_name,d.credit_mobile,d.company')
                  ->join('cash_record b','a.data_id = b.id','left')
                  ->join('shop_user c','a.user_id = c.user_id','left')
                  ->join('credit d','b.card_id = d.credit_id','left')
                  ->where('a.id = '.$id)
                  ->find();
            $status = [
              '1'   => '待处理',
              '2'   => '通过',
              '3'   => '拒绝',
              '4'   => '订单异常'
            ];
            $data['status'] = $status[$data['status']];
        }
        $data['level'] = $level[$data['level']];
        $this->assign('data',$data);
        return $this->fetch();
    }



    /**
     * 通过提现
     */
    public function pass(){
        if($this->request->post()){
            $id = $this->request->post('id');
            $data = Db::name('balance_record')
                  ->alias('a')
                  ->field('a.data_id,b.*')
                  ->join('cash_record b','a.data_id = b.id','left')
                  ->where('a.id = '.$id)
                  ->find();
            if($data['status'] != 1){
               $this->error('该订单状态不可进行成功操作');
            }
            $res = Db::name('cash_record')->where('id',$data['data_id'])->update(['status'=>2]);
            if($res){
                Db::startTrans(); //启动事务
                try {
                    Db::name('shop_user')->where('user_id',$data['user_id'])->setDec('freeze_balance',$data['money']);
                    Db::commit(); //提交事务
                } catch (\PDOException $e) {
                    Db::rollback(); //回滚事务
                }
               $this->success('操作成功');
            }else{
               $this->error('该订单状态修改失败');
            }
        }
    }



    /**
     * 拒绝
     */
    public function reject(){
      if($this->request->post()){
          $id = $this->request->post('id');
          $data = Db::name('balance_record')
                ->alias('a')
                ->field('a.data_id,b.*')
                ->join('cash_record b','a.data_id = b.id','left')
                ->where('a.id = '.$id)
                ->find();
          if($data['status'] != 1){
               $this->error('该订单状态不可进行拒绝操作');
          }
          $res = Db::name('cash_record')->where('id',$data['data_id'])->update(['status'=>3]);
          if($res){
              $user_info = Db::name('shop_user')->where('user_id',$data['user_id'])->find();
              $info = [
                 'balance'        => $user_info['balance'] + $data['money'],
                 'freeze_balance' => $user_info['freeze_balance'] - $data['money'],
              ];
              Db::startTrans(); //启动事务
              try {
                  Db::name('shop_user')->where('user_id',$data['user_id'])->update($info);
                  Db::commit(); //提交事务
              } catch (\PDOException $e) {
                  Db::rollback(); //回滚事务
              }
             $this->success('操作成功');
          }else{
             $this->error('该订单状态修改失败');
          }
      }
    }



    /**
     * 异常
     */
    public function anomaly(){
      if($this->request->post()){
          $id = $this->request->post('id');
          $data = Db::name('balance_record')
                ->alias('a')
                ->field('a.data_id,b.*')
                ->join('cash_record b','a.data_id = b.id','left')
                ->where('a.id = '.$id)
                ->find();
          if($data['status'] != 1){
               $this->error('该订单状态不可进行异常操作');
          }
          $res = Db::name('cash_record')->where('id',$data['data_id'])->update(['status'=>4]);
          if($res){
             $this->success('操作成功');
          }else{
             $this->error('该订单状态修改失败');
          }
      }
    }



    /**
     * 解冻
     */
    public function unfreeze(){
      if($this->request->post()){
          $id = $this->request->post('id');
          $data = Db::name('balance_record')
                ->alias('a')
                ->field('a.data_id,b.*')
                ->join('cash_record b','a.data_id = b.id','left')
                ->where('a.id = '.$id)
                ->find();
          if($data['status'] != 4){
               $this->error('该订单状态不可进行解冻操作');
          }
          $res = Db::name('cash_record')->where('id',$data['data_id'])->update(['status'=>1]);
          if($res){
             $this->success('操作成功');
          }else{
             $this->error('该订单状态修改失败');
          }
      }
    }



    /**
     * 导出
     */
    public function export($list){
        $objPHPExcel = new \PHPExcel();
        $objWriter = new \PHPExcel_Writer_Excel5($objPHPExcel);
        $objWriter = new \PHPExcel_Writer_Excel2007($objPHPExcel);
        // 设置表头信息
        $objPHPExcel->setActiveSheetIndex(0)
        ->setCellValue('A1', '排序')
        ->setCellValue('B1', '订单号')
        ->setCellValue('C1', '用户名')
        ->setCellValue('D1', '支付方式')
        ->setCellValue('E1', '类型')
        ->setCellValue('F1', '金额')
        ->setCellValue('G1', '创建时间')
        ->setCellValue('H1', '状态');
        /*--------------开始从数据库提取信息插入Excel表中------------------*/
        $i=2;  //定义一个i变量，目的是在循环输出数据是控制行数
        $count = count($list);  //计算有多少条数据
        for ($i = 2; $i <= $count+1; $i++) {
            $objPHPExcel->getActiveSheet()->setCellValue('A' . $i, $i-1);
            $objPHPExcel->getActiveSheet()->setCellValue('B' . $i,' '.$list[$i-2]['order_no']);
            $objPHPExcel->getActiveSheet()->setCellValue('C' . $i, $list[$i-2]['mobile']);
            $objPHPExcel->getActiveSheet()->setCellValue('D' . $i, $list[$i-2]['payment_type']);
            $objPHPExcel->getActiveSheet()->setCellValue('E' . $i, $list[$i-2]['group']);
            $objPHPExcel->getActiveSheet()->setCellValue('F' . $i,' '.$list[$i-2]['money']);
            $objPHPExcel->getActiveSheet()->setCellValue('G' . $i, $list[$i-2]['create_time']);
            $objPHPExcel->getActiveSheet()->setCellValue('H' . $i, $list[$i-2]['type']);
        }
        $objPHPExcel->setActiveSheetIndex ( 0 )->getColumnDimension ( 'A' )->setWidth (10);
        $objPHPExcel->setActiveSheetIndex ( 0 )->getColumnDimension ( 'B' )->setWidth (30);
        $objPHPExcel->setActiveSheetIndex ( 0 )->getColumnDimension ( 'C' )->setWidth (20);
        $objPHPExcel->setActiveSheetIndex ( 0 )->getColumnDimension ( 'D' )->setWidth (15);
        $objPHPExcel->setActiveSheetIndex ( 0 )->getColumnDimension ( 'E' )->setWidth (15);
        $objPHPExcel->setActiveSheetIndex ( 0 )->getColumnDimension ( 'F' )->setWidth (15);
        $objPHPExcel->setActiveSheetIndex ( 0 )->getColumnDimension ( 'G' )->setWidth (25);
        $objPHPExcel->setActiveSheetIndex ( 0 )->getColumnDimension ( 'H' )->setWidth (15);

        /*--------------下面是设置其他信息------------------*/

        $objPHPExcel->getActiveSheet()->setTitle('productaccess');      //设置sheet的名称
        $objPHPExcel->setActiveSheetIndex(0);                   //设置sheet的起始位置
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');   //通过PHPExcel_IOFactory的写函数将上面数据写出来   
        $PHPWriter = \PHPExcel_IOFactory::createWriter( $objPHPExcel,"Excel2007");   
        $name = date('Y-m-d',time());
        header('Content-Disposition: attachment;filename="'.$name.'.xlsx"');
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        $PHPWriter->save("php://output"); //表示在$path路径下面生成demo.xlsx文件
        exit;
    }






}